package com.lock.type;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.concurrent.TimeUnit;

/**
 * @Author: tgy
 * @Date: 2020-11-13 11:45
 */

@Data
@AllArgsConstructor
class Chopsticks{

    private String name;


}

@Data
@AllArgsConstructor
public class Philosopher implements Runnable{

    private String name;
    private Chopsticks left;
    private Chopsticks right;

    @Override
    public void run() {

        while (true) {

            synchronized (left) {
                synchronized (right) {

                    // 两根筷子都拿到了，开始吃饭
                    eat();
                    // 休息一会儿
                    rest();
                }

            }

        }

    }

    private void rest() {

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void eat() {

        System.out.println(name + "开始吃饭");
    }


    public static void main(String[] args) {


        Chopsticks c1 = new Chopsticks("c1");
        Chopsticks c2 = new Chopsticks("c2");
        Chopsticks c3 = new Chopsticks("c3");
        Chopsticks c4 = new Chopsticks("c4");
        Chopsticks c5 = new Chopsticks("c5");


        Philosopher p1 = new Philosopher("柏拉图", c1, c2);
        Philosopher p2 = new Philosopher("苏格拉底", c2, c3);
        Philosopher p3 = new Philosopher("毕达哥拉斯", c3, c4);
        Philosopher p4 = new Philosopher("亚里士多德", c4, c5);
        Philosopher p5 = new Philosopher("丢番图", c5, c1);

        new Thread(p1,"t1").start();
        new Thread(p2,"t2").start();
        new Thread(p3,"t3").start();
        new Thread(p4,"t4").start();
        new Thread(p5,"t5").start();

    }
}

























